import { useLocation, useNavigate } from "react-router-dom"
import { findRoute } from "@/utils"
import { useAppSelector } from "@/store"
import {
	saveUserInfoAction,
	saveDynamicRouteListAction,
} from "@/store/modules/user"
import { routers } from "@/router"
import { shallowEqual, useDispatch } from "react-redux"
import { useEffect } from "react"
import type { FC } from "react"
import { reqUserInfo } from "@/api/user"
import { filterRoutes } from "@/utils"
import { dynamicRoutes } from "@/router/routers"
const cloneDeep = require("lodash/cloneDeep")
interface Iprops {
	children?: any
}
/**
 * @description 路由权限组件
 * */
const AuthRouter: FC<Iprops> = (props) => {
	const { token, dynamicRouteList } = useAppSelector(
		(state) => ({
			token: state.userStore.token,
			dynamicRouteList: state.userStore.dynamicRouteList,
		}),
		shallowEqual,
	)
	const dispatch = useDispatch()
	const { pathname } = useLocation()
	const navigate = useNavigate()
	useEffect(() => {
		// 判断有无token
		if (!token.trim()) {
			navigate("/login")
		} else {
			// 判断是否去登录页
			pathname === "/login"
				? navigate("/home", { replace: true })
				: dynamicRouteList !== "[]" // 判断是否有动态路由数据（间接判断有无用户信息）
					? navigate(pathname)
					: reqUserInfo()
							.then((res) => {
								if (res.code === 200) {
									console.log("userinfo", res.data)
									dispatch(saveUserInfoAction(res.data))
									const routes = filterRoutes(
										cloneDeep(dynamicRoutes),
										res?.data?.routes as string[],
									)
									console.log(routes)
									dispatch(saveDynamicRouteListAction(JSON.stringify(routes)))
									navigate(pathname)
								}
							})
							.catch((error) => {
								console.log(error)
							})
		}
	}, [token, pathname])
	// 动态路由
	const dynamicRouters = JSON.parse(dynamicRouteList)
	const constance = ["/login", "/", "/home", "/screen", "/404"].map((path) => {
		return findRoute(path, routers)
	})
	const anyroute = ["*"].map((path) => findRoute(path, routers))
	const routerList = [...constance, ...dynamicRouters, ...anyroute]
	const route = findRoute(pathname, routerList)
	// 路由拦截
	if (Object.keys(route).length === 0) {
		console.log(1111)
		navigate("/404", { replace: true })
	}
	return props.children
}

export default AuthRouter
